﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using GtaAPIClient.TransactionManage;
using GtaAPIClient.WcfRZRJBasicProviderService;
using zbus;

namespace GtaAPIClient
{
    class AccountManage
    {
        WcfService wcfService = null; 
        ServiceConsole.UpdateTextDelegate delg = null;

        
        public AccountManage(ServiceConsole.UpdateTextDelegate delg)
        {
            this.delg = delg;
            delg.BeginInvoke("AccountManage服务初始化成功", null, null);
            wcfService = new WcfServiceImpl();
        } 

        [Remote("openAccount")]
        public OpenAccountReturnMsg openAccount(string username, string loginName, string userPswd, 
                                                string mloginName, string mloginPswd, decimal rmb, decimal hk, decimal usd, 
                                                int accountType, int companyId)
        {
            try
            {
                //1.开户
                InitFund inifund = new InitFund();
                inifund.RMB = rmb;
                inifund.HK = hk;
                inifund.US = usd;

                string outMessage = "";
                TransactionManage.AccountEntity[] accountEntitys = new TransactionManage.AccountEntity[1];
                TransactionManage.UM_UserInfo userInfo = new TransactionManage.UM_UserInfo();
                userInfo.UserName = username;
                userInfo.LoginName = loginName;
                userInfo.Password = userPswd;

                TransactionManage.UM_UserInfo tmp = (TransactionManage.UM_UserInfo)wcfService.openAccount(out accountEntitys, out outMessage, userInfo, inifund, mloginName, mloginPswd);
                OpenAccountReturnMsg rtnUserInfo = new OpenAccountReturnMsg();
                if (tmp == null)
                {
                    rtnUserInfo.IsSuccess = false;
                    rtnUserInfo.Message = outMessage;
                    return rtnUserInfo;
                }
                rtnUserInfo.CouterID = tmp.CouterID;
                rtnUserInfo.LoginName = tmp.LoginName;
                rtnUserInfo.UserName = tmp.UserName;
                rtnUserInfo.UserID = tmp.UserID;
                rtnUserInfo.RoleID = tmp.RoleID;
                rtnUserInfo.Password = tmp.Password;
                rtnUserInfo.Name = tmp.Name;
                rtnUserInfo.Remark = tmp.Remark;

                //2.资金转入证券账号
                int accountTypeBank = 1;
                int accountTypeCapital = 2;
                int currencyTypeRmb = 1;

                //2.1 资金转入沪深A股账号
                if (accountType == 2 || accountType == 4)
                {
                    if (accountType == 4)
                    {
                        accountTypeCapital = 6;
                    }
                    bool succ = wcfService.fundTransfer(out outMessage, rtnUserInfo.UserID, accountTypeBank, accountTypeCapital, rmb, currencyTypeRmb);
                    if (!succ)
                    {
                        rtnUserInfo.IsSuccess = false;
                        rtnUserInfo.Message = outMessage;
                        return rtnUserInfo;
                    }
                }
                //2.2 如果是融资融券账号，则初始化融资融券信息并将资金转入融资融券账号
                else if (accountType == 3)
                {
                    accountTypeCapital = 12;
                    //2.2.1 账户基本信息
                    RZRJ_TraderBasicInfo[] traderBasicInfoList = new RZRJ_TraderBasicInfo[1];
                    RZRJ_TraderBasicInfo bi = new RZRJ_TraderBasicInfo();
                    bi.UserID = rtnUserInfo.UserID;
                    bi.SecurityCompanyID = companyId;
                    bi.TradeAuthority = 63;
                    traderBasicInfoList[0] = bi;
                    int succ = wcfService.addRzrjBasicInfo(out outMessage, traderBasicInfoList);
                    if (succ <= 0)
                    {
                        rtnUserInfo.IsSuccess = false;
                        rtnUserInfo.Message = outMessage;
                        return rtnUserInfo;
                    }

                    //2.2.2 添加信用信息
                    WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit[] modelList = new WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit[2];
                    WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit model = new WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit();
                    model.LimitType = 1;
                    model.EndDate = DateTime.Now.AddYears(10);
                    model.Currency = 1;
                    model.FixedAvailableLimit = 0;
                    model.FixedLimit = 0;
                    model.TotalAvailableLimit = rmb;
                    model.TotalLimit = rmb;
                    modelList[0] = model;

                    model = new WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit();
                    model.LimitType = 2;
                    model.EndDate = DateTime.Now.AddYears(10);
                    model.Currency = 1;
                    model.FixedAvailableLimit = 0;
                    model.FixedLimit = 0;
                    model.TotalAvailableLimit = rmb;
                    model.TotalLimit = rmb;
                    modelList[1] = model;

                    int[] userIdList = new int[1];
                    userIdList[0] = rtnUserInfo.UserID;
                    bool succ2 = wcfService.addRzrjCreditLimit(out outMessage, modelList, userIdList);
                    if (!succ2)
                    {
                        rtnUserInfo.IsSuccess = false;
                        rtnUserInfo.Message = outMessage;
                        return rtnUserInfo;
                    } 

                    //2.2.3 融资融券转账
                    WcfRZRJBasicProviderService.FreeTransferEntity freeTransfer = new FreeTransferEntity();
                    freeTransfer.TraderID = rtnUserInfo.UserID.ToString();
                    freeTransfer.TransferAmount = rmb;
                    freeTransfer.FromCapitalAccountType = accountTypeBank;
                    freeTransfer.ToCapitalAccountType = accountTypeCapital;
                    bool succ3 = wcfService.rzrjFundTransfer(out outMessage, freeTransfer, WcfRZRJBasicProviderService.TypesCurrencyType.RMB);
                    if (!succ3)
                    {
                        rtnUserInfo.IsSuccess = false;
                        rtnUserInfo.Message = outMessage;
                        return rtnUserInfo;
                    }

                } 

                //3.获得资金账号等
                string outMessage2 = "";
                AccountFindResultEntity[] accounts = findAccount(out outMessage2, rtnUserInfo.UserID.ToString(), rtnUserInfo.Password);
                if (accounts != null && accounts.Length > 2)
                {
                    rtnUserInfo.BankAccount = accounts[0].AccountID;
                    rtnUserInfo.CapitalAccount = accounts[1].AccountID;
                    rtnUserInfo.IfAccount = accounts[5].AccountID;
                    if (accountType == 3)
                    {
                        rtnUserInfo.RzrjAccount = accounts[11].AccountID;
                    }
                }

                rtnUserInfo.IsSuccess = true;
                return rtnUserInfo;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("开户失败" + ex.Message, null, null);
                throw new Exception("开户失败", ex);
            }
        }

        /*
        public bool modifyPersonerCreditLimit()
        {
            WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit[] modelList = new WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit[12];
            WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit model = new WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit();

            string[] capitalAccounts = new string[]{"010001351012", 
                                                    "010001350912", 
                                                    "010001350812", 
                                                    "010001350712", 
                                                    "010001350612", 
                                                    "010001350512"};
            int i = 0;
            foreach (string capitalAccount in capitalAccounts) 
            {
                model = new WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit();
                model.CapitalAccount = capitalAccount;
                model.LimitType = 1;
                model.EndDate = DateTime.Now.AddYears(10);
                model.Currency = 1;
                model.FixedAvailableLimit = 0;
                model.FixedLimit = 0;
                model.TotalAvailableLimit = 1000000;
                model.TotalLimit = 1000000;
                modelList[i++] = model;

                model = new WcfRZRJBasicProviderService.RZRJ_PersonLimitCredit();
                model.CapitalAccount = capitalAccount;
                model.LimitType = 2;
                model.EndDate = DateTime.Now.AddYears(10);
                model.Currency = 1;
                model.FixedAvailableLimit = 0;
                model.FixedLimit = 0;
                model.TotalAvailableLimit = 1000000;
                model.TotalLimit = 1000000;
                modelList[i++] = model;
            }

            string outMessage = "";
            bool res = wcfService.modifyRzrjCreditLimit(ref outMessage, modelList);
            return res;
        }*/

        [Remote("findAccount")]
        public AccountFindResultEntity[] findAccount(out string message, string traderId, string password)
        { 
            //delg.BeginInvoke("调用findAccount接口，tradeId=" + traderId, null, null);
            //log("调用findAccount接口，tradeId=" + traderId);
            int accountType = 1;
            try
            {
                return wcfService.findAccount(out message, accountType, traderId, password);
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("查找账户失败" + ex.Message, null, null);
                throw new Exception("查找账户失败", ex);
            }
        }

        [Remote("fundTransfer")]
        public CommonReturnMsg fundTransfer(int tradeId, int fromCapitalAccountType, int toCapitalAccountType, decimal transferAmount, int currencyType)
        {
            string outMessage = ""; 
            try
            {
                bool isSucc = wcfService.fundTransfer(out outMessage, tradeId, fromCapitalAccountType, toCapitalAccountType, transferAmount, currencyType);
                CommonReturnMsg commonReturnMsg = new CommonReturnMsg();
                commonReturnMsg.IsSucess = isSucc;
                commonReturnMsg.Message = outMessage;
                return commonReturnMsg;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("资金转账失败" + ex.Message, null, null);
                throw new Exception("资金转账失败", ex);
            } 
        }

        /// <summary>
        /// 写日志模块，暂未用到
        /// </summary>
        /// <param name="str"></param>
        public void log(string str)
        {
            FileStream fs = new FileStream("../gtalog.txt", FileMode.Create);
            //获得字节数组
            byte[] data = new UTF8Encoding().GetBytes(DateTime.Now + str);
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }
    }

    class CommonReturnMsg
    {
        public bool IsSucess { get; set; }

        public string Message { get; set; } 
    }

    class OpenAccountReturnMsg : TransactionManage.UM_UserInfo
    {
        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public string BankAccount { get; set; }

        public string CapitalAccount { get; set; }

        public string RzrjAccount { get; set; }

        public string IfAccount { get; set; } 

    }
}
